<!--
 * @Author: Dorange.Wang
 * @Date: 2021-04-02 15:06:10
 * @LastEditors: wangming
 * @LastEditTime: 2022-07-27 16:42:26
 * @Description: file content
-->
<template>
  <div>
    <el-row :gutter="12">
      <el-col :span="6">
        <el-autocomplete
          popper-class="autocomplete--custom"
          style="width: 100%"
          :fetch-suggestions="loadPageList"
          placeholder="按Key或名称搜索"
          @select="handlePageSelect"
          :debounce="500"
          prefix-icon="el-icon-search"
          :maxlength="64"
          v-model="queryData.searchKey"
        >
          <template slot-scope="{ item }">
            <div class="header">{{ item.name }}</div>
            <span class="footer">{{ item.key }}</span>
          </template>
        </el-autocomplete>
      </el-col>
      <el-col :span="24" class="mt10">
        <!-- <el-dropdown
          v-if="isDefault"
          @command="handleCreate"
          placement="bottom-start"
          trigger="click"
          size="medium"
        >
          <el-button type="primary">
            新建<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="page">新建</el-dropdown-item>
            <el-dropdown-item command="folder">新建文件夹</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-button
          v-else
          type="primary"
          size="small"
          @click="handleCreate('page')"
          >新建
        </el-button> -->
        <DropdownButtons
          :buttons="[
            {
              icon: 'el-icon-circle-plus-outline',
              command: 'page',
              title: '新建页面',
            },
            {
              icon: 'el-icon-upload2',
              command: 'importPage',
              title: '导入页面',
              upload: {
                accept: '.hm_page',
                httpRequest: handleHttpRequest,
              },
            },
            ...(isDefault
              ? [
                  {
                    icon: 'el-icon-folder-add',
                    command: 'folder',
                    title: '新建文件夹',
                  },
                ]
              : []),
          ]"
          @command="handleCreate"
        />
      </el-col>
    </el-row>
    <template v-if="folderData && folderData.length > 0 && isDefault">
      <div class="mt10" style="height: 1px"></div>
      <el-divider content-position="left">页面管理</el-divider>
      <el-row :gutter="12">
        <el-col :span="6" v-for="folder in folderData" :key="folder.id">
          <el-card class="folder-card mb10" shadow="hover">
            <div class="folder-content" @click="handleFolderClick(folder)">
              <i class="el-icon-folder"></i>
              <span :title="folder.name" class="folder-title">{{
                folder.name
              }}</span>
            </div>
            <el-dropdown
              class="menu"
              placement="bottom"
              trigger="click"
              size="medium"
              @command="handleFolderCommand($event, folder)"
            >
              <i class="el-icon-more"></i>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="edit">编辑</el-dropdown-item>
                <el-dropdown-item command="delete">删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-card>
        </el-col>
      </el-row>
    </template>

    <div class="mt10" style="height: 1px"></div>
    <el-divider v-if="isDefault" content-position="left"
      >默认（{{ total }}）
    </el-divider>
    <el-divider v-else content-position="left">
      <span class="root-link" @click="loadAllData">页面管理</span>
      <i class="el-icon-arrow-right"></i>
      {{ currentFolder.name }}
    </el-divider>
    <el-table
      class="mt10"
      :data="tableData"
      v-loading="loading"
      style="width: 100%"
      current-row-key="id"
      stripe
      border
    >
      <el-table-column prop="key" label="页面Key" width="140">
        <template slot-scope="scope">
          <i
            v-if="!!scope.row.lockBy"
            class="iconfont iconicon_suoguan_gaoliang f16 mr5"
          ></i>
          {{ scope.row.key }}
          <el-button
            style="margin-left: 10px"
            type="text"
            @click="copy(scope.row.key)"
            icon="el-icon-document-copy"
          ></el-button>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="页面名称"></el-table-column>
      <el-table-column prop="description" label="页面描述"></el-table-column>
      <el-table-column prop="modelName" label="模型名称" />
      <el-table-column
        v-if="type === 'FORM'"
        prop="createWay"
        label="表单创建方式"
        width="150"
      >
        <template slot-scope="scope">
          {{ scope.row.createWay | formCreateType }}
        </template>
      </el-table-column>
      <el-table-column prop="modifyDate" label="更新时间" width="180">
        <template slot-scope="scope">
          {{ scope.row.modifyDate | moment }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="300">
        <template slot-scope="scope">
          <span class="table-actionItem">
            <el-button type="text" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
          </span>

          <span class="table-actionItem">
            <el-button type="text" @click="handleCopy(scope.row)"
              >复制</el-button
            >
          </span>
          <span class="table-actionItem">
            <el-button type="text" @click="handleMove(scope.row)"
              >移动</el-button
            >
          </span>

          <span class="table-actionItem">
            <el-button type="text" @click="handleDesign(scope.row)"
              >设计</el-button
            >
          </span>
          <span class="table-actionItem">
            <el-popconfirm
              title="确定要删除该页面吗？"
              placement="top"
              @confirm="handleDelete(scope.row)"
            >
              <el-button class="link-danger" type="text" slot="reference"
                >删除</el-button
              >
            </el-popconfirm>
          </span>
          <span class="table-actionItem"
            ><el-button type="text" @click="handleExport(scope.row)"
              >导出</el-button
            ></span
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="tr mt24">
      <x-pagination
        :total="total"
        :pageSize.sync="pageData.pageSize"
        :pageNo.sync="pageData.pageNo"
        @search="loadData"
      ></x-pagination>
    </div>

    <CopyForm ref="CopyForm" />
  </div>
</template>

<script>
import { appUnique, Accesstoken } from "@/utils/auth";
import CommonForm from "./commonForm";

import {
  getHmpagePageList,
  deleteHmpage,
  postHmpageCopy,
  getHmpageExport,
  postHmpageImport,
} from "@/apis/paas/HmPageController.js";
import {
  getHmpagefolderList,
  deleteHmpagefolder,
} from "@/apis/paas/HmPageFolderController.js";
import CopyForm from "./CopyForm";
import { copy, exportAppDataFromJson } from "@/utils/util";
import DropdownButtons from "@/components/DropdownButtons/Index.vue";
import FolderForm from "./folderForm";
import MoveForm from "./moveForm";
export default {
  name: "CommonList",
  components: { CopyForm, DropdownButtons },
  props: {
    type: {
      type: String,
      default: "",
    },
  },

  data() {
    return {
      copy,
      loading: false,
      queryData: {},
      pageData: {
        pageSize: 10,
        pageNo: 1,
      },
      tableData: [],
      total: 0,
      folderData: [],
      currentFolder: {
        id: this.DEFAULT_FOLDER,
      },
    };
  },
  computed: {
    isDefault() {
      return this.currentFolder.id === this.DEFAULT_FOLDER;
    },
    DEFAULT_FOLDER() {
      return this.type === "ALL" ? 1 : 2;
    },
  },
  created() {
    const {
      currentFolderId,
      currentFolderName,
      currentFolderType,
      type,
      pageNo,
      pageSize,
    } = this.$route.query;
    this.currentFolder.id = Number(currentFolderId);
    this.currentFolder.name = currentFolderName;
    this.currentFolder.type = currentFolderType;
    if (currentFolderType !== this.type) {
      this.currentFolder = {};
    }
    if (pageSize) {
      this.pageData.pageSize = Number(pageSize);
    }
    if (pageNo) {
      this.pageData.pageNo = Number(pageNo);
    }
    this.loadData();
    this.loadFolderData();
  },
  methods: {
    loadData() {
      if (!this.currentFolder.id) {
        this.pageData.pageNo = 1;
        this.currentFolder = {
          id: this.DEFAULT_FOLDER,
          type: this.type,
        };
      }
      getHmpagePageList({
        ...this.queryData,
        ...this.pageData,
        folderId: this.currentFolder.id,
        type: this.type,
      }).then((res) => {
        this.tableData = res.data;
        this.total = res.totalCount;
        this.$router.replace({
          ...this.$route,
          query: {
            type: this.type.toLowerCase(),
            ...this.pageData,
            currentFolderId: this.currentFolder.id,
            currentFolderName: this.currentFolder.name,
            currentFolderType: this.type,
          },
        });
      });
    },

    loadFolderData() {
      getHmpagefolderList({ type: this.type }).then((res) => {
        this._folderData = res || [];
        this.folderData = res.filter((item) => item.id !== this.DEFAULT_FOLDER);
      });
    },

    handleReset() {
      this.queryData = {};
      this.loadData();
    },

    handleCreate(command) {
      if (command === "page") {
        const { type } = this;
        CommonForm.addForm({
          folderId: this.currentFolder.id,
          type,
        }).then(({ createWay, name, modelId, id, modelCode }) => {
          this.handleDesign({ modelName: name, id, modelId, name, modelCode });
          this.$message.success("新增成功");
        });
      } else if (command === "folder") {
        FolderForm.addForm({}, this.type).then(() => {
          this.$message.success("新增成功");
          this.loadFolderData();
        });
      }
    },

    handleEdit(record) {
      const { type } = this;
      CommonForm.editForm({
        ...record,
        type,
      }).then(() => {
        this.loadData();
        this.$message.success("操作成功");
      });
    },

    handleCopy(record) {
      const {
        id: pageId,
        modelId,
        modelName,
        name,
        description,
        modelCode,
      } = record;
      this.$refs.CopyForm.open(
        {
          name,
          description,
          modelId,
        },
        (data) => {
          postHmpageCopy({
            ...data,
            pageId,
          }).then((res) => {
            this.handleDesign({ modelName, id: res, modelId, name, modelCode });
            this.$message.success("操作成功");
            this.$refs.CopyForm.close();
          });
        }
      );
    },
    getRootUrl(toPort) {
      const { origin, port } = window.location;
      if (port) {
        return origin.replace(port, toPort);
      }
      return origin;
    },
    handleDesign(
      { modelName, id, modelId, name, modelCode },
      type = this.type
    ) {
      switch (type) {
        case "LIST":
          this.$router.push({
            name: "designForList",
            query: { modelName, id, modelId, name },
          });
          break;
        case "FORM":
          this.$router.push({
            name: "design",
            query: { modelName, id, modelId, name },
          });
          break;
        case "ALL":
          this.$router.push({
            name: "designUniversal",
            query: { modelName, id, modelCode, name },
          });
          break;
        case "APP": {
          this.loadData();
          let url = `${
            location.port
              ? location.origin.replace(location.port, "8888")
              : location.origin
          }${location.pathname.replace(
            "designer",
            "mdesigner"
          )}?token=${Accesstoken.getAccessToken()}#/designer/${id}`;
          window.open(url);
          break;
        }
        default:
          this.$router.push({
            name: "designUniversal",
            query: { modelName, id, modelId, name },
          });
          break;
      }
    },

    handleDelete(record) {
      deleteHmpage([record.id]).then((res) => {
        this.loadData();
        this.$message.success("操作成功");
      });
    },
    handleFolderEdit(record) {
      FolderForm.editForm(record).then(() => {
        this.loadFolderData();
        this.$message.success("操作成功");
      });
    },

    handleFolderCommand(command, record) {
      if (command === "edit") {
        this.handleFolderEdit(record);
      } else if (command === "delete") {
        this.handleFolderDelete(record);
      }
    },

    handleFolderDelete(record) {
      deleteHmpagefolder([record.id]).then((res) => {
        this.loadFolderData();
        this.$message.success("操作成功");
      });
    },

    // 点击文件夹
    handleFolderClick(folder) {
      this.currentFolder = folder;
      this.currentFolder.type = this.type;
      this.pageData.pageNo = 1;
      this.loadData();
    },
    // 默认文件夹下的数据
    loadAllData() {
      this.currentFolder = {
        id: this.DEFAULT_FOLDER,
        name: "",
      };
      this.pageData.pageNo = 1;
      this.loadData();
    },
    loadPageList(query = "", callback) {
      const emptyData = [];
      const searchKey = query.trim();
      if (!query.trim()) {
        callback(emptyData);
        return;
      }
      getHmpagePageList({
        pageSize: 30,
        pageNo: 1,
        searchKey,
      }).then((res) => {
        callback(res.data);
      });
    },

    handlePageSelect(item) {
      this.handleDesign(item, item.type);
    },
    handleMove(record) {
      MoveForm.editForm(record, {
        type: this.type,
        folderList: this._folderData,
      }).then(() => {
        this.loadData();
        this.$message.success("操作成功");
      });
    },

    /**
     * 导出
     * @param {*} record
     */
    async handleExport(record) {
      const res = await getHmpageExport({
        pageId: record.id,
      });
      await exportAppDataFromJson({
        data: res,
        key: `${record.key}_${this.type === "APP" ? "APP" : "PC"}`,
        ext: "hm_page",
      });

      setTimeout(() => {
        this.$message.success("导出成功");
      }, 1500);
    },

    /**
     * 导入
     * @param {*} file
     */
    async handleHttpRequest(file) {
      const formData = new FormData();
      formData.append("file", file.file);
      await postHmpageImport(formData, { folderId: this.currentFolder.id });
      this.$message.success("导入成功");
      this.loadData(1);
    },
  },
};
</script>

<style lang="scss" scoped>
.el-dropdown-menu {
  min-width: 100px;
}

.folder-card {
  border: 1px solid #dcdfe6;
  position: relative;
  cursor: pointer;

  ::v-deep .el-card__body {
    padding: 0;

    .folder-content {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      padding: 20px;
      box-sizing: border-box;
    }

    .menu {
      position: absolute;
      top: 10px;
      right: 10px;
    }

    .el-icon-folder {
      font-size: 38px;
      color: #999;
      margin-right: 10px;
    }

    .el-icon-more {
      font-size: 18px;
      color: #999;
    }

    .folder-title {
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
    }
  }
}

.root-link {
  color: #409eff;
  cursor: pointer;
  margin-right: 5px;
  font-weight: bold;
}
</style>
